package com.pi.smart.base.task;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.pi.base.concurrent.BaseExecutors;
import com.pi.base.enumerate.redis.RedisCacheEnum;
import com.pi.base.util.cache.RedisUtil;
import com.pi.smart.client.ins.bed.annotation.ForBedIns;
import com.pi.smart.client.ins.bed.category.BedInsEnum;
import com.pi.smart.client.ins.bed.domain.SmartBedCmd;
import com.pi.smart.client.ins.bed.variety.BedInsHandler;

/**
 * @description 记录睡眠日志
 * @author chenmfa
 */
@Component
public class UserSleepLogTask {
  private static final Logger logger = LoggerFactory.getLogger(UserSleepLogTask.class);

  private static volatile boolean isRunning = true;
  @Autowired
  private List<BedInsHandler> bedTaskHandlers;
  private static Map<BedInsEnum, BedInsHandler> bedTaskHandlerMap = new ConcurrentHashMap<>();
  
  @PostConstruct
  public void initDataLogger(){
    logger.info("[rolling_logger]开始启动棉被日志记录器：{}", System.currentTimeMillis());
    preProcessBedTask();
    BaseExecutors.executor.submit(() -> {
      while(isRunning){
        try {
          readLog();
        }catch(Exception e) {
          logger.error("处理睡眠指令失败", e);
        }
      }
    });
  }
  private void readLog(){
    SmartBedCmd cmd = null;
      try {
        cmd = RedisUtil.blpop(RedisCacheEnum.SMART_BED_CMD_COMMON);
      } catch (ClassNotFoundException | IOException e) {
        logger.error("获取指令记录失败：", e);
        return;
      }
      if(null == cmd){
        try {Thread.sleep(3000);} catch (InterruptedException e){}
        return;
      }else{
        logger.info("[DEV_SLEEP_SCAN]查询设备指令数据- {}", cmd);
      }
      if(null == cmd.getInsEnum()){
        logger.error("指令类型为空, {}", JSON.toJSONString(cmd));
        return;
      }
      if(bedTaskHandlerMap.containsKey(cmd.getInsEnum())){
        bedTaskHandlerMap.get(cmd.getInsEnum()).process(cmd);
      }else{
        logger.error("未定义的指令：{}", JSON.toJSONString(cmd));
      }
  }
  
  private void preProcessBedTask(){
    if(null == bedTaskHandlers){
      return;
    }
    for(BedInsHandler bedInsHandler : bedTaskHandlers){
      ForBedIns annotation = bedInsHandler.getClass().getAnnotation(ForBedIns.class);
      if(null != annotation){
        bedTaskHandlerMap.putIfAbsent(annotation.ins(), bedInsHandler);
      }
    }
  }
  
  public static void shutdownTask(){
    isRunning = false;
  }
}
